<?php
/**
 * Created by PhpStorm.
 * User: LiuJiaJun
 * Date: 2019/1/13
 * Time: 11:34
 */

namespace api\storage\service;


use api\storage\common\Constant;
use api\storage\model\ContainersModel;
use api\storage\model\InflowModel;
use api\storage\model\PurchaseDetailModel;
use api\storage\model\ReelsModel;
use api\storage\model\SeatModel;
use app\storage\model\ContainerModel;

class ContainerService extends BaseService
{

    private $containersModel;

    public function __construct()
    {
        $this->containersModel = new ContainersModel();
    }

    /**
     * 将物料放在容器中
     * @param $code
     * @param $reelIds
     * @param $storageUuid
     * @param $nickname
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function putReelIdIntoContainer($code, $reelIds, $storageUuid, $nickname)
    {
        $containerInfo = $this->containersModel->findByContainerCode($code);
        //判断容器是否是已经上架了，如果上架的话，那么要插入入库流水
        $status = $containerInfo->getData('status') == 1 ? 1 : 0;
        $purchaseDetailModel = new PurchaseDetailModel();

        $reelsInfo = $purchaseDetailModel->queryReels($reelIds, $storageUuid);
        if($this->isEmpty($reelsInfo)){
            return $this->resultTemplate(2);
        }
        //$uuid用来记录已经装箱的reels的uuid，相当于是换箱子，那么将原来的数据清除，在重新写入一条
        $reelsData = $inflowData = $uuid = [];
        foreach ($reelsInfo as $item) {
            //如果装箱的物料已经在架子上了，那么就不需要装了。
            if ($item->getData('container_code') == $code) {
                continue;
            }
            $reelsData[] = $tempItem = ReelsService::generateReels($item->getData('reel_id'), $item->getData('sub_materiel_id'),
                $item->getData('count'), $containerInfo->getData('seat_code'), $code, $storageUuid, $status);
            if (!empty($item->getData('reel_uuid'))) {
                array_push($uuid, $item->getData('reel_uuid'));
            }
            if ($status == 1) {
                $inflowData[] = InflowService::generateInflow($tempItem, $nickname);
            }
        }

        $reelsModel = new ReelsModel();
        $inflowModel = new InflowModel();
        $reelsModel->startTrans();

        $deleteRes = $this->isEmpty($uuid) ? true : $reelsModel->deleteByUuidList($uuid);
        $reelsRes = $this->isEmpty($reelsData) ? true : $reelsModel->insertAll($reelsData);
        $inflowRes = $this->isEmpty($inflowData) ? true : $inflowModel->insertAll($inflowData);
        if ($deleteRes === false || empty($reelsRes) || empty($inflowRes)) {
            $reelsModel->rollback();
            return $this->resultTemplate(0);
        } else {
            $reelsModel->commit();
            return $this->resultTemplate(1);
        }
    }

    /**
     * 查找容器的内容
     *
     * @param $code
     * @param $storageUuid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function queryContainerData($code, $storageUuid)
    {
        //查找容器是否存在
        $container = $this->containersModel->findByContainerCode($code);
        if (empty($container)) {
            return $this->resultTemplate('-1');
        }
        //查询reels的对应的容器的信息
        $reelModel = new ReelsModel();
        $reels = $reelModel->queryByContainerCodeAndUuid($code, $storageUuid);
        return $this->resultTemplate(1, $reels->toArray());
    }

    /**
     * 容器站位检查
     *
     * @param $seatCode
     * @param $code
     * @param $storageUuid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkSeatCode($seatCode, $storageUuid)
    {
        $seatModel = new SeatModel();
        $type = $seatModel->getSeatType($seatCode, $storageUuid);
        if (empty($type)) {
            return $this->resultTemplate(-2);
        }
        if ($type !== Constant::SHELF_TYPE_OF_CONTAINER) {
            return $this->resultTemplate(-1);
        }
        $reelsModel = new ReelsModel();
        $containers = $reelsModel->queryContainers($seatCode, $storageUuid);
        return $this->resultTemplate(1, $containers);
    }

    /**
     * 容器站位绑定
     *
     * @param $seatCode
     * @param $code
     * @param $storageUuid
     * @param $nickname
     * @return array
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bindSeatWithContainer($seatCode, $code, $storageUuid, $nickname)
    {
        $container = $this->containersModel->findByContainerCode($code);

        $reelsModel = new ReelsModel();
        $reelsModel->startTrans();
        $reelsInfos = $reelsModel->queryReelsInfo($code, $storageUuid);
        $seatModel = new SeatModel();
        $seatRes = $seatModel->updateIsUsed($seatCode, $storageUuid);
        $containerRes = $this->containersModel->updateByCode($code, ['status' => 1, 'seat_code' => $seatCode]);
        $reelRes = $inflowRes = true;
        if ($container->getData('seat_code') != $seatCode) {
            $reelsInfos = $this->isNotEmpty($reelsInfos) ? $reelsInfos->toArray() : [];
            foreach ($reelsInfos as $reelsInfo) {
                //如果在装箱的时候已经上架了，那么就不需要写流水了
                if ($reelsInfo['status'] != 1) {
                    $inflowData[] = InflowService::generateInflow($reelsInfo, $nickname);
                }
                $reelRes = $reelsModel->updateReel($reelsInfo['reel_id'], $storageUuid, ['status' => 1, 'seat_code' => $seatCode]);
                //为false 的话就是出现了错误，没有必要再继续执行下去了
                if ($reelRes === false) {
                    break;
                }
            }
        }
        if (!empty($inflowData)) {
            $inflowModel = new InflowModel();
            $inflowRes = $inflowModel->insertAll($inflowData);
        }
        if (empty($inflowRes) || $seatRes === false || $containerRes === false || $reelRes === false) {
            $reelsModel->rollback();
            return $this->resultTemplate(0);
        } else {
            $reelsModel->commit();
            return $this->resultTemplate(1);
        }
    }
}